const HtmlWebpackPlugin = require('html-webpack-plugin'); //通过 npm 安装
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const path = require('path');

const config = {
    entry: {
        index: './src/index.js'
    },
    output: {
        filename: 'assets/js/[name].[hash].js',
        path: path.resolve(__dirname, 'dist')
    },
    devServer: {
        contentBase: path.join(__dirname, "dist")
    },
    module: {
        rules: [{
                test: /\.(sa|sc|c)ss$/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                    options: {
                        publicPath: '../../'
                    }
                }, {
                    loader: 'css-loader'
                }, {
                    loader: 'sass-loader'
                }]
            }, {
                test: /\.css$/,
                use: [{
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../../'
                        }
                    },
                    "css-loader"
                ]
            },
            {
                test: /\.(png|svg|jpg|gif|woff|woff2|eot|ttf|otf)$/,
                loader: 'file-loader',
                options: {
                    name: 'assets/img/[hash].[ext]'
                }
            }
        ]
    },
    plugins: []
};

for (key in config.entry) {
    config.plugins.push(new HtmlWebpackPlugin({
        filename: `${key}.html`, //打包好后，新建的html名字为first.html
        template: `./src/temp/${key}.html`, //以src下面的index.html为模板去创建新的html文件
        hash: true,
        chunks: [key],
        favicon: './favicon.ico',
        minify: {
            removeComments: true,
            collapseInlineTagWhitespace: true,
            collapseWhitespace: true
        }
    }))
}

config.plugins.push(new MiniCssExtractPlugin({
    filename: 'assets/css/[name].[hash].css',
    chunkFilename: 'assets/css/[id].[hash].css',
}))

config.plugins.push(new OptimizeCssAssetsPlugin())

module.exports = config;